#include "receiveudp.h"

receiveudp::receiveudp(QObject *parent) :
    QObject(parent)
{
    receiver = new QUdpSocket(this);
    udpPort = 54545;
    receiver->bind(udpPort, QUdpSocket::ShareAddress);

    connect(receiver, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagram()));

}

receiveudp::~receiveudp()
{
    if (receiver)
    {
        receiver->close();
        receiver->deleteLater();
    }
}

void receiveudp::setPort(const qint16 &port)
{
    udpPort = port;
}

void receiveudp::processPendingDatagram()
{
    while(receiver->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(receiver->pendingDatagramSize());
        receiver->readDatagram(datagram.data(), datagram.size());

        QDataStream in(&datagram, QIODevice::ReadOnly);
        in >> ipAddress >> message;

        emit getBroadMessage(message);
        qDebug() << ipAddress << message;
    }
}
